import "./reset.css";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { AssetItem } from "./types";
import { cloneDeep } from "@pureadmin/utils";
import { computed, ref, type Ref, reactive } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import editForm from "../form/index.vue";
import { ElMessageBox } from "element-plus";

export function useAsset(tableRef: Ref) {
  const form = reactive({
    assetName: "",
    assetId: "",
    type: "",
    dealerId: "",
    SearchTerm: "",
    OrderBy: ""
  });

  const dataList = ref<AssetItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "名称",
      prop: "name",
      minWidth: 130
    },
    {
      label: "编号",
      prop: "code",
      minWidth: 90
    },
    {
      label: "类型",
      prop: "typeName",
      minWidth: 120,
      cellRenderer: scope => {
        const typeName = scope.row.typeName;
        const typeClass = typeName === "普通音频文件" ? "primary" : "success";
        return (
          <el-tag type={typeClass} size="small">
            {typeName}
          </el-tag>
        );
      }
    },
    {
      label: "URI",
      prop: "uri",
      minWidth: 200
    },
    {
      label: "租户ID",
      prop: "tenantId",
      minWidth: 90
    },
    {
      label: "租户名称",
      prop: "tenantName",
      minWidth: 130
    },
    {
      label: "经销商ID",
      prop: "dealerId",
      minWidth: 90
    },
    {
      label: "经销商名称",
      prop: "dealerName",
      minWidth: 130
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 150
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  //删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否确认删除资产编号为${row.id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Asset/Delete"), {
            data: { id: row.id }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除资产编号为${row.id}的数据`, { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }
  //播放
  function handlePlay(row) {
    message(`播放资产: ${row.name}`, { type: "info" });
    // 这里可以添加实际的播放逻辑
  }
  //下载
  function handleDownload(row) {
    message(`下载资产: ${row.name}`, { type: "info" });
    // 这里可以添加实际的下载逻辑
  }
  //页面数据大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }
  //处理页码变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  //处理选择变化
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }
  //取消选择
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  //批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Asset/BatchDelete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }
  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  //搜索
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      assetName: form.assetName,
      assetId: form.assetId,
      type: form.type,
      dealerId: form.dealerId
    };

    http
      .post(changeHttpLink("/api/Asset/List"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          // 处理类型名称显示
          res.Data.Items.forEach(item => {
            item.typeName = item.type === 1 ? "普通音频文件" : "TTS";
          });
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //新增
  function openDialog(type = "新增", row = {}) {
    const result = addDialog({
      title: `${type}资产`,
      props: {
        form: cloneDeep(row),
        type
      },
      width: "600px",
      draggable: true,
      contentRenderer: () => editForm
    });

    if (result && typeof result.then === "function") {
      result.then(() => {
        onSearch();
      });
    } else {
      onSearch();
    }
  }
  //修改
  function handleUpdate(row) {
    console.log(row);
  }
  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }

  // 初始化加载数据
  onSearch();

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handlePlay,
    handleDownload,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
